/// this the main canvas class , which creates the tab and the columns for plugins
var Canvases = new Class(
{
    options: { },
    canvasArr: [],
    initialize: function()
    {
            this.num_canvases = 0;
    },
    ///// add a new tab and a page, send in name, number of columns and the icon, and other settings
    addCanvas: function(name, columns, icon, allowConfig, allowClose, fixedColumn, eventCode, clearModule, pageNumber, isPreset, isNew, boxWidth, autoFit, isSlideShow, intIntervalSlideShow){
            if( pageNumber === undefined || pageNumber === null ){
                //find larger no by looping through
                if(this.num_canvases >1){
                    var noOfTabs = [];
                    var otherConf;
                    var spll, y;

                    for(i=1; i <= this.num_canvases; i++){
                        if($defined($('tab_box'+i))){
                            /*
                            y = $('tab_box'+i).innerHTML;
                            spll = y.split("<!--");
                            spll = spll[1].split("-->");
                            var pdata = JSON.decode(html_entity_decode(spll[0]));
                            noOfTabs.push( pdata.pageNumber );			//page no for all the widgets to put
                            */
                            y = $('tab_box'+i).getElement('.tab_title').getProperty('data');
                            var pdata = JSON.decode(y);
                            noOfTabs.push( pdata.pageNumber );
                        }
                    }

                    noOfTabs.sort(sortTabsNumbers);
                    if(noOfTabs.length>0){
                        if(noOfTabs){
                            this.pageNumber = parseInt(noOfTabs[0] , 10)+1;
                        }else{
                            this.pageNumber = this.num_canvases+1;
                        }
                    }else{
                        this.pageNumber=1;
                        pgWidgets=0;
                        pgWidgetsTotal = pgWidgets;
                    }
                }else if(this.num_canvases === 1){
                    this.pageNumber = this.num_canvases;
                }else{
                    this.pageNumber=1;
                    pgWidgets=0;
                    pgWidgetsTotal = pgWidgets;
                }
            }else{
                this.pageNumber = pageNumber;
            }

            if(wfc_globalModules[this.pageNumber]){
                wfc_globalModules[this.pageNumber]=[];
            }
            this.num_canvases = this.pageNumber;
            if(name ===  undefined || name === null){
                name = lang.label("upperpage")+" "+ this.pageNumber;
            }
            if(columns === undefined || columns === null ){
                columns = '3-0';
            }
            if(icon === undefined || icon === null ){
                icon = '';
            }
            this.name        = name;
            this.columns     = columns;
            this.icon        = icon;
            this.allowConfig = $defined(allowConfig) ? allowConfig: true;
            this.allowClose  = $defined(allowClose) ? allowClose: true;
            this.boxWidth  = boxWidth;
            this.autoFit  = autoFit;
            this.fixedColumn = fixedColumn;
            this.eventCode   = eventCode;
            this.clearModule = clearModule;
            this.isSlideShow = isSlideShow;
            this.intIntervalSlideShow = intIntervalSlideShow;

            if(isPreset === undefined || isPreset === null){
                this.isPreset = false;
            }else{
                this.isPreset = isPreset;
            }

            //set this var is the page is new
            this.isNew = isNew;

            this.drawTab();
    },

    //// save page info
    savePages: function()
    {
        var str2 = "";
        var pdataArray = [];
        var alltabs = $('tab_panel').getChildren();
        var ttabs = alltabs.length;
        for(var i = 0 ; i < ttabs ; i++)
        {
            var idd = alltabs[i].id;
            if( (idd !== 'tab_box') && (idd.contains('tab_box')))
            {
                var mee = idd.replace(/tab_box/i , "");
                //pnt = $('tab_title'+mee).innerHTML;
                /*
                Check the Tab element to prevent the js error form any possibility operations.
                */
                if($('tab_title'+mee) == null)
                {
                    break;
                }
                pnt = $('tab_title'+mee).getProperty('data');
                var icn = '';

                if( $defined($('tab_icon_icn'+mee)) )
                {
                    icn = $('tab_icon_icn'+mee).src;
                    var spll = icn.split('img/default/');
                    icn = spll[1];
                }
                /*
                var spll2 = pnt.split("<!--");
                pn = spll2[0];
                spll2 = spll2[1].split("-->");
                */
                var pdata = JSON.decode(pnt);

                if(pdata.isPreset === "true")		//it saves additional text to identify the preset pages.
                {
                    pn = "~PSP~" + pdata.name;
                }
                else
                {
                    pn = pdata.name;
                }
                str2 += (i + 1) + '<::>' + pdata.name + '<::>' + pdata.columns + '<::>' + icn + '<::>'+ pdata.allowConfig +'<::>'+ pdata.allowClose +'<::>'+ pdata.fixedColumn +'<::>'+ pdata.eventCode +'<::>'+ pdata.pageNumber+'<::>'+ pdata.isSlideShow+'<::>'+ pdata.intIntervalSlideShow +'<||>\n';
                pdataArray[i] = {sqeuenceNumber:(i + 1), pageName:pn, layout:pdata.columns, icon:icn, allowConfig:pdata.allowConfig, allowClose:pdata.allowClose, fixedColumn:pdata.fixedColumn, eventCode:pdata.eventCode, pageNumber:pdata.pageNumber, boxWidth:pdata.boxWidth, autoFit:parseInt(pdata.autoFit,10), isSlideShow:parseInt(pdata.isSlideShow,10), intIntervalSlideShow:parseInt(pdata.intIntervalSlideShow,10), container_id: wfcid};

                var x="";
            }
        }

        /// set the cookie based on response , if logged in make sure its destroyed on window close
        if(ud !== "ok")
        {
            Cookie.set('UDP', str2 , {path: wf_cookie_path});
        }
        else
        {
            //sendData(dbHandler, "&act=pdata&data="+str2, gonull);
            sendData(dbHandler, JSON.encode({act:'pdata', pdata:pdataArray, cid: wfcid}), gonull);
        }

    },

    checkName: function(mid, ttl, layout,checkonly)
    {
            //check the tab name, can't contain these word.
            var valid_name=true;
            var reLeading = /\s*((\S+\s*)*)/;
            var reTrailing= /((\s*\S+)*)\s*/;
            var varReplace = ttl.replace(reLeading, "$1");
            if( varReplace === "" || varReplace === null )
            {
                // Move this to PagePros/module.js
                // alert(lang.label('empty_title'));
                $('opttabtitle').select();
                return false;

            }

            if(!valid_name)
            {
                $('opttabtitle').select();
                return false;
            }
            else
            {
                if(!checkonly)
                {
                    wfc_mainScreen.adjustSetts(mid, ttl.replace(reLeading, "$1").replace(reTrailing, "$1"), layout);
                }
                if($defined($(optopen)))
                {
                    $(optopen).remove();
                }
                optopen = '';
            }
            return true;
    },

    //// adjust the number of columns and the layout
    adjustSetts: function(mid , ttl, layout)
    {
                    // Terrence, for special layout.
                    // (after review all code, the layout always pass in ''; so we can use it.
                    layout = wfc_getSelectedLayout();
                    //////////////////////////////////////////////////////////////////////

                    //this will be called from the top bar above, always set this to true.

                    pnt = $('tab_title'+mid).innerHTML;
                    var spll = pnt.split("<!--");
                    pn = spll[0];
                    spll = spll[1].split("-->");

                    var pdata = JSON.decode(html_entity_decode(spll[0]));
                    pageNumber = pdata.pageNumber; //page no for all the widgets to put
                    var ud;

                    if(layout === "" || layout === null )
                    {
                        layout="3-0";
                    }

                    currTabTitle=ttl;		//set the title to this on.

                    pdata.columns = layout;
                    pdata.allowConfig = true;
                    pdata.allowClose = true;
                    pdata.name = currTabTitle;
                    var page_config = (wfc_loc_pageName ? (TM_ProductLang.label(currTabTitle)) : (currTabTitle)) + "<!--" + (JSON.encode(pdata)) + "-->";
                    //var page_config = (wfc_loc_pageName ? htmlentities(TM_ProductLang.label(currTabTitle)) : htmlentities(currTabTitle)) + "<!--" + layout +'~true~true~'+ ud +'~'+ ud +'~'+ pageNumber+'~'+ ud +'~'+ htmlentities(currTabTitle)+"-->";
                    $('tab_title'+mid).setProperty('data',JSON.encode(pdata));
                    $('tab_title'+mid).setHTML(page_config);

                    //alert(currTabLayout);
                    // Terrence 12/05/09, for table layout style
                    if (wfc_is_table_layout_style(currTabLayout))
                    {
                        wfc_adjust_settings(mid, ttl);
                        //Roger 12/11/2009 new table layout doesn't need to assign new Drag and Drop event handlers again
                        //because there is no old column layout will have more columns issue
                        return;
                    }
                    ////////////////////////////////////////////////////////////////////////////////

                    // if the layout is different than the current one , go into block
                    if(currTabLayout !== layout)
                    {

                        //alert( currTabLayout +' ' + layout);

                        var p  = layout.split('-');
                        var op = currTabLayout.split('-');

                        var childs = $('cttr'+this.currActive).getChildren();
                        var hm = childs.length;

                        //// if columns are same but different layout
                        if(op[0] === p[0])
                        {
                            for(var x = 0 ; x < hm ; x++)
                            {
                                var width = 0;
                                if(p[1] === '0' && p[0] === "3")
                                {
                                    width = xl3[x];
                                }
                                if(p[1] === '0' && p[0] === "2")
                                {
                                    width = xl2[x];
                                }
                                if(p[1] === '0' && p[0] === "1")
                                {
                                    width = xl1;
                                }
                                if(p[1] === '1' && p[0] === "3")
                                {
                                    width = xl6[x];
                                }
                                //if(p[1] == '1' && p[0] == "3" && x == 1) width = '50%';
                                //if(p[1] == '1' && p[0] == "3" && x == 2) width = '25%';

                                if(p[1] === '1' && p[0] === "2")
                                {
                                    width = xl5[x];
                                }
                                //if(p[1] == '1' && p[0] == "2" && x == 1) width = '70%';

                                if(p[1] === '2' && p[0] === "2")
                                {
                                    width = xl7[x];
                                }
                                //if(p[1] == '2' && p[0] == "2" && x == 1) width = '30%';

                                //check if the width is =='all'
                                if(width === 'all')
                                {
                                    width="";
                                }
                                //alert(width);
                                childs[x].setProperty('width', width);
                            }
                        }
                        else
                        { // if number of columns has changed

                            //// if greater columns are required
                            currTabLayout = layout;
                            if(p[0] > op[0])
                            {
                                var n = this.currActive;
                                for(var x1 = 0 ; x1 < p[0] ; x1++)
                                {
                                    var width_second = 0;
                                    //alert(p[1]);

                                    if(p[1] === '0' && p[0]=== "4")
                                    {
                                        width_second = xl4[x1];
                                    }
                                    if(p[1] === '0' && p[0]=== "3")
                                    {
                                        width_second = xl3[x1];
                                    }
                                    if(p[1] === '0' && p[0]=== "2")
                                    {
                                        width_second = xl2[x1];
                                    }
                                    if(p[1] === '0' && p[0]=== "1")
                                    {
                                        width_second = xl1;
                                    }
                                    if(p[1] === '1' && p[0] === "3")
                                    {
                                        width_second = xl6[x1];
                                    }
                                    //if(p[1] == '1' && p[0]== "3" && x == 1) width_second = '50%';
                                    //if(p[1] == '1' && p[0]== "3" && x == 2) width_second = '25%';

                                    if(p[1] === '1' && p[0]=== "2")
                                    {
                                        width_second = xl5[x1];
                                    }
                                    //if(p[1] == '1' && p[0]== "2" && x == 1) width_second = '70%';

                                    if(p[1] === '2' && p[0]=== "2")
                                    {
                                        width_second = xl7[x1];
                                    }
                                    //if(p[1] == '2' && p[0]== "2" && x == 1) width_second = '30%';

                                    // looop through the columns and see if we need to create the column or just update its layout

                                    //check if the width_second is =='all'
                                    if(width_second === 'all')
                                    {
                                        width_second="";
                                    }

                                    //alert(width_second);

                                    if((x1+1) > op[0])
                                    {
                                        new Element('td', {'id':'cttd'+n+x1 , 'class':'droppables'}).injectInside('cttr'+n);
                                        //$('cttd'+n+x1).setStyle('border', '2px dotted #cccccc');
                                        $('cttd'+n+x1).setProperty('width', width_second);
                                        $('cttd'+n+x1).setStyle('vertical-align', 'top');
                                        $('cttd'+n+x1).setProperty('height', '200');
                                        //$('cttd'+n+x).setHTML("&nbsp;");
                                    }
                                    else
                                    {
                                        $('cttd'+n+x1).setProperty('width', width_second);
                                    }
                                }


                                /// add the droppable events

                                var fx = null;
                                var drag = this.boxObject;
                                //$$('div.window').removeEvents();
                                $$('div.window').each(function(drag)
                                {
                                    var childs = drag.getChildren();
                                    var hndl;
                                    for(var x = 0 ; x < childs.length ; x++)
                                    {
                                        if(childs[x].getProperty('class') === "handler")
                                        {
                                            hndl = childs[x];
                                            hndl.removeEvents('mousedown');
                                            break;
                                        }
                                    }
                                            if (hndl === undefined || hndl === null )
                                            {
                                                return;
                                            }
                                var dragBox = null;

                                hndl.addEvents(
                                {
                                'mousedown' : function(event)
                                {
                                            // console.log('mousedown');
                                            if (iambz === true)
                                            {
                                                return;
                                            }
                                            if (dragBox === null)
                                            {
                                                return;
                                            }
                                            var eventlocal = new Event(event);
                                            if (eventlocal.target.id.contains('adiv') === true)
                                            {
                                                dontfire=true;    // edit, min/max, refresh and delete icon don't fire.
                                            }
                                            else
                                            {
                                                dontfire=false;   // others, prepare drag drop
                                                dragBox.start(eventlocal);   // ask drag class to start again.
                                            }
                                    }
                                }
                                ); // end of mousedown event handler

                                dragBox =	new Drag.Move(drag, {
                                        'handle': hndl, 'droppables': $$('td.droppables') ,

                                        onStart: function(el){
                                            if (dontfire === true)
                                            {
                                                // don't prpergate event to next and clean up.
                                                this.stop();
                                                el.setStyle('zIndex' ,'0');
                                                dragging = false;
                                                dragwhich=null;
                                                dragcord = null;
                                                dragtarget=null;
                                                dragstep=0;
                                            }
                                            else
                                            {
                                                // prepare to drag drop
                                                dragcord = el.getCoordinates();
                                                dragging = true;
                                                dragwhich=el.id;
                                            }
                                        },

                                        onBeforeStart: function(el){
            // console.log('onBeforeStart el.id='+el.id);
                if (iambz === true)
                {
                    return;
                }
                // Terrence 03/13/2009 because onBeforeStart event cannot distinguish element.
                // It is possible click on drag/drop, refresh, min/max, edit, delete icons.
                // Must wait mousedown to set dragwhich.
                if (MooTools['version'].contains('1.2') === true)
                {
                    if ((dragwhich === undefined) || (dragwhich === null))
                    {
                        dragwhich=el.id;    // mousedown event haven't fire yet. so return.
                        return;
                    }
                }
                // this is second time onBeforeStart come in.
                dragwhich=el.id;
                if(dontfire === false)
                {
                    if($defined( $('temppp'+dragwhich) ) )
                    {
                        $('temppp'+dragwhich).remove();
                    }
                    dragcord = el.getCoordinates();
                    var parenttd = el.getParent();
                    var nextdiv = el.getNext('div'); // Avoid IMG element

                    $$('div.window').setStyle('zIndex' , '0');

                    el.setStyle('zIndex' , '1000');
                    el.setStyle('left' , dragcord.left);
                    el.setStyle('top' , dragcord.top);
                    el.setStyle('width' , dragcord.width);
                    el.setStyle('position' , 'absolute');

                    if(nextdiv === undefined || nextdiv === null)
                    {
                        new Element('div', {'id':'temppp'+dragwhich , 'class':'window'}).injectInside($(parenttd));
                    }
                    else
                    {
                        new Element('div', {'id':'temppp'+dragwhich , 'class':'window'}).injectBefore($(nextdiv));
                    }

                    $('temppp'+dragwhich).setStyle("height" , (dragcord.height - 2));
                    $('temppp'+dragwhich).setStyle("width" , dragcord.width);
                    $('temppp'+dragwhich).setHTML("&nbsp;");
                    $('temppp'+dragwhich).setStyle("border" , '1px dotted red');

                    // Terrence 03/30/09; fix a bug:
                    //  2 widgets in column 1; 2 widget in column 3; move 1 widget from 1 to 3.
                    //  Move 1 widget from 1 to 1. The widget will jump to column 3.
                    // Because these 3 variable don't re-initial.
                    cloneunder = null;
                    cloneover = null;
                    cloneinside = null;
                    //

                }
                else
                {
                    if($defined( $('temppp'+dragwhich) ) )
                    {
                        $('temppp'+dragwhich).remove();
                    }
                }
                el.fireEvent('BeforeDrag', null);
                                        },

                                        onComplete: function(el)
                                        {
                                            //el.setStyle('zIndex' ,'0'); dragging = false;dragwhich=null; dragcord = null;dragtarget=null;dragstep=0;
                                        },

                                            // user just click and no move
            onCancel: function(el)
            {
                // console.log(el, ' onCancel');
                if (iambz === true)
                {
                    return;
                }
                if( dragwhich !== undefined && dragwhich !== '' && dragwhich !== null)
                {
                    $(dragwhich).setStyle('position' , 'relative');
                    $(dragwhich).setStyle('left' , 0);
                    $(dragwhich).setStyle('top' , 0);
                    if($defined( $('temppp'+dragwhich) ) )
                    {
                        $('temppp'+dragwhich).remove();
                    }
                }
                // onComplete, (in Mootools 1.2, it won't fire onComplete event).
                el.setStyle('zIndex' ,'0');
                el.setStyle('width','100%');
                dragging = false;dragwhich=null; dragcord = null;dragtarget=null;dragstep=0;
            },

            onDrag: function(el)
            {
                // console.log(el, 'onDrag');
                dragstep++;
                if(dragging && dragstep%4 === 0)
                {
                    var pos = $(dragwhich).getCoordinates();
                    var childtds = $('cttr'+wfc_mainScreen.currActive).getChildren();
                    var incol = null;
                    var halfwd = Math.ceil(pos.width/2);
                    var maxperc = 0;

                    for(var x =0 ; x < childtds.length ; x++)
                    {
                        var tdobj = childtds[x];
                        var tdcord = tdobj.getCoordinates();

                        var inhere = 0;
                        var maxleft = Math.max(tdcord.left , pos.left);
                        var maxright = Math.min(tdcord.right , pos.right);

                        if(maxleft >= tdcord.left){
                            inhere = tdcord.right - maxleft;
                        }

                        if(tdcord.left >= maxleft){
                            inhere = maxright - tdcord.left;
                        }

                        //console.log(' inhere '+ inhere);

                        if(inhere < 0)
                        {
                            continue;
                        }

                        var perc = (inhere/pos.width) * 100;

                        if(perc > maxperc) {
                            maxperc = perc;
                            incol = tdobj;
                        }
                    }

                    if(incol === undefined || incol === null)
                    {
                        return false;
                    }
                    dragtarget = incol.id;

                    if(dragtarget === undefined || dragtarget === null )
                    {
                        return false;
                    }

                    var noDrag = $(dragtarget).hasClass('nondroppables');
                    if(noDrag)
                    {
                        //console.log(' not allowed '+ dragtarget);
                        return false;
                    }
                    // Get all DIVs except IMG element in target column
                    var colchilds = $(dragtarget).getChildren('div');
                    var coltotals = colchilds.length;
                    var minusht = 0;
                    var addon = -1;
                    var remove = false;
                    var updn = 0;
                    var i = -1;
                    var already = false;
                    var ccord;

                    // Terrence 03/25/09
                    // Fix a bug that when drag from 1 child column to others
                    //  while drag back to original column, the red box won't show.
                    // This is because the child count of original column should be minus 1.
                    // Without minus 1; the coltotals is incorrect.
                    // Check: if the target column is the original colum of dragwhich, minus one from coltotals.
                    if ($defined($(dragwhich).parentNode))
                    {
                        if ($(dragwhich).parentNode.id === $(dragtarget).id)
                        {
                            if (coltotals === 1)
                            {
                                coltotals--;
                            }
                        }
                    }
                    //
                    for( i=0 ; i < coltotals ; i++)
                    {
                        if (colchilds[i].id === $(dragwhich).id)
                        {
                            continue;
                        }

                        ccord = colchilds[i].getCoordinates();

                        if(colchilds[i].id === 'temppp'+dragwhich)
                        {
                            //minusht = ccord.height;
                            already = true;
                            continue;
                        }

                        var halfht = ccord.top + (Math.ceil((ccord.height)/2) - minusht);
                        if( (pos.top  > (ccord.top - minusht) && pos.top < halfht))
                        {
                            if(cloneshown && cloneover === colchilds[i].id)
                            {
                                already = true;
                            }
                            updn = 1;
                            break;
                        }

                        if( (pos.top < (ccord.bottom - minusht) && pos.top > halfht))
                        {
                            if(cloneshown && cloneunder === colchilds[i].id)
                            {
                                already = true;
                            }

                            updn = 2;
                            break;
                        }
                    }


                    if(updn === 0 && coltotals !== 0 && already !== true)
                    {
                        var topone = colchilds[0].getCoordinates();
                        var bottomone = colchilds[(coltotals - 1)].getCoordinates();

                        if(pos.top > topone.top)
                        {
                            i = 0;
                            if(cloneshown && cloneover === colchilds[i].id)
                            {
                                already = true;
                            }
                            updn = 1;
                        }

                        if(pos.top > bottomone.bottom)
                        {
                            i = (coltotals-1);
                            if(cloneshown && cloneunder === colchilds[i].id)
                            {
                                already = true;
                            }
                            updn = 2;
                        }
                    }

//                        console.log("already:" + already + " i=" + i + " coltotals=" + coltotals + " updn=" + updn);
                    if((already === true && i === 1) || i === -1 || coltotals === 0)
                    {
                        if($defined( $('temppp'+dragwhich) ) )
                        {
                            $('temppp'+dragwhich).remove();
                        }
                        new Element('div', {'id':'temppp'+dragwhich}).injectInside($(dragtarget));
                        $('temppp'+dragwhich).setStyle("border" , '1px dotted red');
                        $('temppp'+dragwhich).setStyle("height" , pos.height);
                        $('temppp'+dragwhich).setHTML("&nbsp;");
                        cloneshown = true;
                        cloneinside = dragtarget;
                        cloneunder = null;
                        cloneover = null;
                        return true;
                    }

                    if( updn === 1 && i > -1)
                    {
                        if(pos.top > dragcord.top && pos.top < dragcord.bottom && ( colchilds[i].getParent().id === $(dragwhich).getParent().id ))
                        {
                            return true;
                        }

                        if($defined( $('temppp'+dragwhich) ) )
                        {
                            $('temppp'+dragwhich).remove();
                        }
                        new Element('div', {'id':'temppp'+dragwhich}).injectBefore(colchilds[i]);
                        $('temppp'+dragwhich).setStyle("border" , '1px dotted red');
                        $('temppp'+dragwhich).setStyle("height" , pos.height);
                        $('temppp'+dragwhich).setHTML("&nbsp;");
                        cloneshown = true;
                        cloneover = colchilds[i].id;
                        cloneunder = null;
                        cloneinside = null;
                        return true;
                    }

                    if( updn === 2 && i  > -1)
                    {
                        if(pos.top > dragcord.top && pos.top < dragcord.bottom && ( colchilds[i].getParent().id === $(dragwhich).getParent().id ))
                        {
                            return true;
                        }
                        if($defined( $('temppp'+dragwhich) ) )
                        {
                            $('temppp'+dragwhich).remove();
                        }
                        new Element('div', {'id':'temppp'+dragwhich}).injectAfter(colchilds[i]);
                        $('temppp'+dragwhich).setStyle("border" , '1px dotted red');
                        $('temppp'+dragwhich).setStyle("height" , pos.height);
                        $('temppp'+dragwhich).setHTML("&nbsp;");
                        cloneshown = true;
                        cloneunder = colchilds[i].id;
                        cloneover = null;
                        cloneinside = null;
//							console.log("injectAfter");
                        return true;
                    }

                    // console.log(' coming till here '+ dragtarget);

                    if(already !== true)
                    {
                        cloneshown = false;
                        cloneunder = null;
                        cloneover = null;
                        cloneinside = null;
                    }
                }
            },
                            // Mootools 1.2
    onDrop: function(el, obj)
    {
        if(iambz === true)
        {
            return ;
        }
        iambz = true;
        var mydragwhich=dragwhich;
        // Terrence 03/15/09; add drag/drop visual effect
        var fx = new Fx.Morph(el, {
            duration:wfc_dragdrop_effectDuration,
            wait:false,
            onComplete: function(){
                        if($defined( $('temppp'+mydragwhich) ) ) {
                            $('temppp'+mydragwhich).remove();
                }

            if (mydragwhich !== null && mydragwhich !==undefined)
            {
                    // Terrence 03/27/09; add [src, dst] to afterDrop signal.
                    var dst = null;
                    var src = $(mydragwhich).parentNode.id;
                    if(this.innerHTML === "&nbsp;")
                    {
                        this.setHTML("");
                    }
                    // decide where to insert; maybe no place change. (no inject)
                    if(cloneinside !== undefined && cloneinside !==null)
                    {
                        dst = cloneinside;
                        el.injectInside(cloneinside);
                    }
                    else if(cloneover !== undefined && cloneover  !== null)
                    {
                        dst = $(cloneover).parentNode.id;
                        el.injectBefore(cloneover);
                    }
                    else if(cloneunder !== undefined && cloneunder !== null)
                    {
                        dst = $(cloneunder).parentNode.id;
                        el.injectAfter(cloneunder);
                    }

                    // change the stlye back to normal.
                    el.setStyle('position','relative');
                    el.setStyle('left','0px');
                    el.setStyle('top','0px');
                    el.setStyle('width','100%');
                    el.setStyle('zIndex','0');

                    var tbl = el.id.replace(/sbox/i , '');
                    $('insettbl'+tbl).fireEvent('mouseout');
                    // Terrence 03/27/09; user defined event for widget handler to redraw.
                    // src: source column; dst: destination column.
                    if (dst !== null && dst !== undefined)
                    {
                        el.fireEvent('AfterDrop', [src, dst], 100);
                    }
                } // end of if (dragwhich != null);
                //
                setTimeout("saveUD()" , 100);
                // onComplete, (in Mootools 1.2, it won't fire onComplete event). clean up
                el.setStyle('zIndex' ,'0');
                dragging = false;dragwhich=null; dragcord = null;dragtarget=null;dragstep=0;
            } // end of onComplete.
        }); // end of new Fx.Morph

        // start move to destination
        if(wfc_dragdrop_effectOnOff&&$defined( $('temppp'+dragwhich)))
        {
            fx.start({
                'left': $('temppp'+dragwhich).getLeft(),
                'top': $('temppp'+dragwhich).getTop()
            });
            dragging = false;
            dragcord = null;
            dragtarget=null;
            dragstep=0;
        }
        else
        {
            // strange here, must be mouse move out of browser and move in.
            fx.fireEvent('complete', null);
        }
    }   // end of onDrop
                                    });


                                    drag.addEvents({
                                        'emptydrop' : function(){

                if( dragwhich !== undefined && dragwhich !== '' && dragwhich !== null)
                {
                    $(dragwhich).setStyle('position' , 'relative');
                    $(dragwhich).setStyle('left' , 0);
                    $(dragwhich).setStyle('top' , 0);

                    if($defined( $('temppp'+dragwhich) ) )
                    {
                        $('temppp'+dragwhich).remove();
                    }
                }

                                                    }
                                    });
                                });

                                $$('td.droppables').removeEvents();
                                            // mootools 1.1
        $$('td.droppables').each(function(drop, index)
        {
            drop.addEvents({
                'drop': function(el, obj){
                    if(iambz === true)
                    {
                        return ;
                    }
                    iambz = true;

                    if($defined( $('temppp'+dragwhich) ) )
                    {
                        $('temppp'+dragwhich).remove();
                    }
                    //else return true;

                    if(this.innerHTML === "&nbsp;")
                    {
                        this.setHTML("");
                    }

                    if(cloneinside !== undefined && cloneinside !== null)
                    {
                        el.injectInside(cloneinside);
                    }
                    else if(cloneover !== undefined && cloneover !== null)
                    {
                        el.injectBefore(cloneover);
                    }
                    else if(cloneunder !== undefined && cloneunder !== null)
                    {
                        el.injectAfter(cloneunder);
                    }

                    el.setStyle('position','relative');
                    el.setStyle('left','0px');
                    el.setStyle('top','0px');
                    el.setStyle('width','100%');
                    el.setStyle('zIndex','0');

                    var tbl = el.id.replace(/sbox/i , '');
                    $('insettbl'+tbl).fireEvent('mouseout');
                    el.fireEvent('AfterDrop', [obj]);
                    setTimeout("saveUD()" , 50);
                } // end of drop
            }); // end of addEvent.
        }); // end of each.







                            }
                            else
                            { /////// if the columsn needed is lower than now
                                var currActiveNumber = this.currActive;
                                for(var xPageNo = 0 ; xPageNo < parseInt(op[0],10) ; xPageNo++)
                                {
                                    var widgetCurrentPage = 0;

                                    if(p[1] === '0' && p[0]=== "4")
                                    {
                                        widgetCurrentPage = xl4[xPageNo];
                                    }
                                    if(p[1] === '0' && p[0]=== "3")
                                    {
                                        widgetCurrentPage = xl3[xPageNo];
                                    }
                                    if(p[1] === '0' && p[0]=== "2")
                                    {
                                        widgetCurrentPage = xl2[xPageNo];
                                    }
                                    if(p[1] === '0' && p[0]=== "1")
                                    {
                                        widgetCurrentPage = xl1;
                                    }
                                    if(p[1] === '1' && p[0]=== "3" )
                                    {
                                        widgetCurrentPage = xl6[xPageNo];
                                    }
                                    //if(p[1] == '1' && p[0]== "3" && x == 1) widgetCurrentPage = '50%';
                                    //if(p[1] == '1' && p[0]== "3" && x == 2) widgetCurrentPage = '25%';

                                    if(p[1] === '1' && p[0]=== "2" )
                                    {
                                        widgetCurrentPage = xl5[xPageNo];
                                    }
                                    //if(p[1] == '1' && p[0]== "2" && xPageNo == 1) widgetCurrentPage = '70%';

                                    if(p[1] === '2' && p[0]=== "2")
                                    {
                                        widgetCurrentPage = xl7[xPageNo];
                                    }
                                    //check if the widgetCurrentPage is =='all'
                                    if(widgetCurrentPage==='all')
                                    {
                                        widgetCurrentPage="";
                                    }
                                    //alert(widgetCurrentPage);

                                    $('cttd'+currActiveNumber+xPageNo).setProperty('width', widgetCurrentPage);

                                    var mods = $('cttd'+currActiveNumber+xPageNo).getElements('div[id^=sbox]');
                                    var mhm = mods.length;
                                    var stay = true;

                                    if((xPageNo + 1) > p[0])
                                    {
                                        stay = false;
                                    }
                                    // calculate where the unneeded column plugin boxes will go
                                    if(stay === false)
                                    {
                                        if(mhm > 0)
                                        {
                                            var _goto = 'cttd'+currActiveNumber+'0';
                                            var colMath;
                                            if(p[0] === 3)
                                            {
                                                colMath = Math.ceil(mhm/p[0]);
                                            }
                                            else if(p[0] === 2)
                                            {
                                                colMath = Math.ceil(mhm/p[0]);
                                            }
                                            else
                                            {
                                                colMath = mhm;
                                            }

                                            for(var y = 0 ; y < mhm ; y++)
                                            {
                                                if( y === colMath)
                                                {
                                                    _goto = 'cttd'+currActiveNumber+'1';
                                                }
                                                mods[y].injectInside($(_goto));
                                            }
                                            $('cttd'+currActiveNumber+xPageNo).remove();
                                        }
                                        else{
                                            $('cttd'+currActiveNumber+xPageNo).remove();
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //alert('set now');

                    currTabLayout = layout;

                    /// save user data
                    saveUD();
                    //wfc_mainScreen.savePages();
                },



        // add tab and page layout
        drawTab: function()
        {
            var DrawTabEvent = function()
            {
                inCol = this.id;
            };

            this.num_canvases++;
            var tabPageNumber = this.pageNumber;

            var dTabBox = new Element('li', {'class': 'tab_box clearfix',	'id': 'tab_box'+tabPageNumber } ).injectBefore('tab_box');
            new Element('div', {'class': 'tab_left','id':'tab_left'+tabPageNumber}).injectInside('tab_box'+tabPageNumber);
            new Element('div', {'class': 'tab_middle clearfix','id':'tab_middle'+tabPageNumber}).injectAfter('tab_left'+tabPageNumber);
            new Element('div', {'class': 'tab_icon','id':'tab_icon'+tabPageNumber}).injectInside('tab_middle'+tabPageNumber);

            dTabBox.addEvents({
                'mouseover': function(event){
                    this.addClass('hover');
                },
                'mouseout': function(event){
                    this.removeClass('hover');
                }
            });

            if(this.icon !== '' && this.icon !== null && this.icon !== undefined && this.icon !== 'undefined'){
                $('tab_icon'+tabPageNumber).setHTML('<img id="tab_icon_icn'+tabPageNumber+'" src="img/default/'+ this.icon +'"/>');
            }

            if(this.eventCode=== undefined || this.eventCode==='undefined' || this.eventCode===null || this.eventCode==='null'){
                new Element('div', {  'class': 'tab_title','id':'tab_title'+tabPageNumber}).injectAfter('tab_icon'+tabPageNumber);
            }else{
                new Element('div', {'class': 'tab_title','id':'tab_title'+tabPageNumber}).injectAfter('tab_icon'+tabPageNumber);

                //this is for custom event handler.
                $('tab_title'+tabPageNumber).addEvent('click', function(){
            	    alert('tab_title'+tabPageNumber);
                    var spll = this.innerHTML.split("<!--");
                    spll = spll[1].split("-->");

                    var pdata = JSON.decode(html_entity_decode(spll[0]));

                    if (pdata.eventCode !== undefined || pdata.eventCode !== 'undefined'){
                        document.location.href = pdata.eventCode;
                    }
                });
            }
            //save the config here so, we get when looping through
            var pdata = {
                columns: this.columns,
                allowConfig: this.allowConfig,
                allowClose: this.allowClose,
                fixedColumn: this.fixedColumn,
                eventCode: this.eventCode,
                pageNumber: this.pageNumber,
                isPreset: this.isPreset,
                name: this.name,
                boxWidth: this.boxWidth,
                autoFit: this.autoFit,
                isSlideShow: this.isSlideShow,
                intIntervalSlideShow: this.intIntervalSlideShow
            };
            var page_config = (wfc_loc_pageName ? (TM_ProductLang.label(this.name)) : (this.name)) + "<!--" + (JSON.encode(pdata)) +"-->";
            //var page_config = (wfc_loc_pageName ? htmlentities(TM_ProductLang.label(this.name)) : htmlentities(this.name)) + "<!--" + this.columns +'~'+ this.allowConfig +'~'+ this.allowClose +'~'+ this.fixedColumn +'~'+ this.eventCode +'~'+ this.pageNumber +"~"+ this.isPreset +"~"+ htmlentities(this.name)+"-->";
            $('tab_title'+tabPageNumber).setProperty('data',JSON.encode(pdata));
            $('tab_title'+tabPageNumber).setHTML(page_config);
            //alert('page conf ' + page_config);

            new Element('div', {'class': 'tab_controls','id':'tab_controls'+tabPageNumber}).injectAfter('tab_title'+tabPageNumber);
            //if the allowClose config is set to false, show no config button
            if(this.allowClose)
            {
                new Element('div', {'events':	{'mousedown':function(event){event.stopPropagation(); wfc_mainScreen.removeCanvas(this.id) ; } },'class': 'tab_close_btn','id':'tab_close_btn'+tabPageNumber, 'title':lang.labelText('close_tab')}).injectInside('tab_controls'+tabPageNumber);
            }
            else
            {
                new Element('div', {'style': 'height:7px;width:0px;','id':'tab_close_btn'+tabPageNumber}).injectInside('tab_controls'+tabPageNumber);
            }

            //if the config is set to false, show no config button
            if(this.allowConfig)
            {
                new Element('div', {'events': {'click':function(){ wfc_mainScreen.cSettings(this.id) ; } }, 'class': 'tab_options_btn','id':'tab_options_btn'+tabPageNumber}).injectInside('tab_controls'+tabPageNumber);
            }
            else
            {
                new Element('div', {'style': 'height:7px; width:0px;','id':'tab_options_btn'+tabPageNumber}).injectInside('tab_controls'+tabPageNumber);
            }


            new Element('div', {'class': 'tab_right', 'id':'tab_right'+tabPageNumber}).injectAfter('tab_middle'+tabPageNumber);
            new Element('div', {'id':'canvas'+tabPageNumber,'class':'canvas'}).injectInside('page_body');
            //$('canvas'+tabPageNumber).setStyle('display', 'none');

            // check if min-width works
            var ddd = new Element('div',{'style':'width:200px;min-width:300px'}).inject(document.body);
            wfc_has_minwidth = ddd.offsetWidth>200;
            ddd.destroy();

            //generate layout
            wfc_layout[this.pageNumber] = new WFLayout({'type':this.columns,'pageNumber':this.pageNumber,'boxWidth':this.boxWidth});

            this.activeCanvas('tab_title'+tabPageNumber,'none');
        },

    checkActive: function(id)
    {
        if(allowClick===false)
        {
            return;
        }
        //var cls=$("tab_box"+id).getProperty("class");

        if(!$("tab_box"+id).hasClass('tab_box_selected'))
        {
            this.activeCanvas('tab_title'+id,'load');
        }
    },

    // set active page
    activeCanvas: function(whichone, toLoad)
    {
        if( $defined( $(whichone) ))
        {
            var tab_settings = $(whichone).get('data');
            //alert(tab_settings);
            whichone = whichone.replace(/tab_title/i , "");

            //var spll = tab_settings.split("<!--");
            //pn   = spll[0];
            //pll = spll[1].split("-->");


            var pdata = JSON.decode(tab_settings);
            var pageNumber = pdata.pageNumber;		 //page no for all the widgets to put

            if(this.clearModule)                 //if new tab is added;
            {
                modules=[];
            }

            if(toLoad === 'none')
            {		//if only tab is clicked just make it visible
                if(this.isNew)
                {
                    wfc_mainScreen.savePages();
                    pgWidgets=0;
                    pgWidgetsTotal = pgWidgets;
                }
                this.activateTabOnly(tab_settings, whichone, toLoad);

                //active new tab and  update variables which may be used by  new tab
                if(this.isNew){
                    this.pageNumber = pageNumber;
                    wfc_globalModules[this.pageNumber]=[];
                    this.clearModule = false;
                    this.isNew = false;
                    this.activeCanvas("tab_title"+this.pageNumber,"load");
                }

                return;
            }
            else if(toLoad ==='first_load'){		//don not load if it is already loaded from preset pages funciton.
                this.isNew=true;
                this.activateTabOnly(tab_settings, whichone, toLoad);
                return;
            }
            else		//else.. do all including and creating part
            {
                //here.. get the data from talker.php

                if(toLoad==='del')
                {
                    allowClick=false;
                    this.activateTabOnly(tab_settings, whichone);

                    //if(! isInArray(visitedTabs, whichone)){
                    var icn = $('tab_icon_icn'+whichone);
                    if(icn)
                    {
                        $('tab_icon_icn'+whichone).setStyle('display', 'none');
                    }
                    $('tab_icon'+whichone).setHTML( $('tab_icon'+whichone).innerHTML +" <img src='img/default/loadingSmall.gif' id='tab_icon_temp"+whichone +"' />" );
                    sendData(dbHandler, JSON.encode({act:'getModule', pid:pageNumber}), this.createTabs, {pid:pageNumber});

                    return;
                }

                if(toLoad==="load")	{		//remove the cookie and it will set below
                    allowClick=true;
                    pgWidgets=0;
                    pgWidgetsTotal = pgWidgets;
                    calltime = 0;  //reset calltine when changing tab
                }


                if(isInArray(visitedTabs, whichone))
                {	//if the user has visited this page earlier.. then its fine
                    this.activateTabOnly(tab_settings, whichone);
                    WF.util.InitWidget();
                    if(isInArray(inCompleteTabs, parseInt(whichone))){
                        inCompleteTabs.erase(parseInt(whichone));
                        $$('#canvas'+whichone+' .layout').fireEvent('autofit');
                    }     
                    WF.util.RefreshWidgetTitleEllipsis();
                }
                else
                {

                    this.activateTabOnly(tab_settings, whichone);
                    var icnNumber = $('tab_icon_icn'+whichone);
                    if(icnNumber)
                    {
                        $('tab_icon_icn'+whichone).setStyle('display', 'none');
                    }
                    $('tab_icon'+whichone).setHTML( $('tab_icon'+whichone).innerHTML +" <img src='img/default/loadingSmall.gif' id='tab_icon_temp"+whichone +"' />" );

                    //try to show msg in the tab.. or an icon
                    sendData(dbHandler, JSON.encode({act:'getModule', pid:pageNumber}), this.createTabs, {pid:pageNumber});

                    allowClick=false;

                    return;
                }
            }
        }
    },

    createTabs: function(dataObj)
    //createTabs: function(dataStr, dataObj)
    {
        var udataArray = Array();
        if (dataObj[0])
        //if (dataObj)
        {
            udataArray = JSON.decode(dataObj[0]).result;
            widgets = "";
            if (udataArray !== "")
            {
                udataArray.each(function(udata)
                {
                    widgets	+=	udata.modname	+	':'	+
                                udata.column + ':' +
                                udata.wid + ':' +
                                udata.showMin + ':' +
                                udata.showClose + ':' +
                                udata.showSetting + ':' +
                                udata.showHelp + ':' +
                                udata.allowDrag + ':' +
                                udata.UniqueCss + ':' +
                                udata.page + ':' +
                                udata.order + ':' +
                                udata.widget_key + "|";
                });
            }

            createFirstTabWidgets(this.options.VoidObj.pid, true);
        }

        if (!isInArray(visitedTabs, lastTab))
        {
            visitedTabs.push(wfc_mainScreen.currActive);
        }
    },

    activateTabOnly: function(tab_settings, whichone, toLoad)
    {
            $$('#tab_panel li').each(function(item,index){
                item.setProperty('class','tab_box');
            });
            $$('#page_body .canvas').each(function(item,index){
                if (item.Fx) {
                    item.Fx.cancel();
                }
                
                item.setStyles({
                    opacity: 0,
                    'z-index': -9,
                    visibility: 'hidden',
                    position: 'absolute'
                });
            });
            
            var tab = $('tab_box'+whichone);
            tab.setProperty('class','tab_box_selected');
            
            if (isSlideShowOn) {
                var parentUl = tab.getParent('ul'),
                    wrapperWidth = parentUl.getParent('div.wrapper').getSize().x,
                    leftBound = parseInt(parentUl.getStyle('margin-left'), 10) * -1,
                    rightBound = leftBound + wrapperWidth,
                    tabMeasure = tab.measure(function() {
                                    var x = this.getPosition(parentUl).x;
                                    return {
                                        l: x,
                                        r: x + this.getSize().x
                                    }
                                });
                if (tabMeasure.l < leftBound || tabMeasure.r > rightBound) {
                    var offset = ((tabMeasure.l < leftBound) ? tabMeasure.l : tabMeasure.r - wrapperWidth) * -1;
                    parentUl.setStyle('margin-left', offset + 'px');
                }
            }
            
            var div = $('canvas'+whichone).setStyles({ 
                opacity: 0,
                'z-index': 9,
                position: 'relative'
            });

            if (div.Fx) {
                div.Fx.start(1);
            } else {
                div.Fx = new Fx.Style(div, 'opacity', { duration: 1000 }).start(1);
            }
            
            if(optopen !== "" && this.currActive !== whichone)
            {
                if($defined($(optopen)))
                {
                    $(optopen).remove();
                }
                optopen = "";
            }
            
            //var spll = tab_settings.split("<!--");

            //spll = spll[1].split("-->");
            var pdata = JSON.decode(tab_settings);
            currTabTitle = pdata.name;


            this.currActive = whichone;
            
            currTabNumb = whichone;
            
            currTabLayout = pdata.columns;
            
			var cname = Cookie.get("cname",{path: wf_cookie_path});
			if(wfc_remember_lasttab.contains(cname))
			{
				Cookie.set("lastTab", pdata.pageNumber, {path: wf_cookie_path});
			}

            activeTabModule = wfc_globalModules[wfc_mainScreen.currActive];
            
            if(activeTabModule)
            {
                pgWidgets=0;
                activeTabModule.each(function(module, id)
                {
                    if(module !== undefined || module !== "")
                    {
                        if(module)
                        {
                            pgWidgets++;
                        }
                    }
                });
                pgWidgetsTotal = pgWidgets;
                modules = activeTabModule;
            }
            
            //Roger 6/3/2009 check if there is a dirty flag set, if yes then notify to redraw
            if($defined($('tab_box'+wfc_mainScreen.currActive)))
            {
                if( $('tab_box'+wfc_mainScreen.currActive).getAttribute('NeedResize')==='1'){
                    wfc_fireEventToAllActiveWidgets("AfterResize",null);
                    $('tab_box'+wfc_mainScreen.currActive).setAttribute('NeedResize','0');
                }
            }

            wfc_fireEventToAllActiveWidgets("AfteractivateTab",null);
    },

    // remove a page and its columns
    removeCanvas: function(whichone)
    {
        if( $defined( $(whichone) ) )
        {
        	WF.util.stopSlideShow();
            if(confirm(lang.labelText('menu_delete_prompt')))
            {
                wfc_fireEventToAllActiveWidgets("BeforeRemoveTab",null);
                modules = [];
                wfc_globalModules[wfc_mainScreen.currActive] = [];
                pgWidgets = 0;
                whichone = whichone.replace(/tab_close_btn/i, "");

                $('tab_box'+whichone).remove();
                
                var canvas = $('canvas'+whichone);
                canvas.getElements('div.box > table.widget').each(function (item) {
                    if (item.timer) {
                        clearTimeout(item.timer.tId);
                        item.timer = null;
                        try {
                            delete item.timer;
                        } catch (ex) {
                        }
                    }
                });
                
                canvas.remove();

                Array.remove(visitedTabs, whichone);
                Array.remove(inCompleteTabs, parseInt(whichone));
                wfc_layout[wfc_mainScreen.currActive] = null;

                ////// save the pages and names, icon, layout etc
                wfc_mainScreen.savePages();

                // Find 1st tab
                var FirstTab = GetFirstTabID();

                if (FirstTab > 0)
                {
                    wfc_mainScreen.activeCanvas("tab_title"+FirstTab, "load");
                }
                else
                {
                    wfc_mainScreen.activeCanvas("tab_title1", "del");
                }

                //this.num_canvases = (this.num_canvases-1);
                //alert(this.num_canvases);
                sendData(dbHandler, JSON.encode({act:'delTab', pid:whichone}), gonull);
                $('tab_panel').setStyle('margin-left','0');
                window.fireEvent('tab_change');
            }
        }
    } ,

    /// clear all of the pages
    clear: function(){
        for(i=1; i <= this.num_canvases ; i++){
            if($defined($('tab_box'+i))) {
                $('tab_box'+i).remove();
                $('canvas'+i).remove();
            }
        }
        this.num_canvases = 0;
    },

    //////////////////////////////////////////////////////////////////////////////////////////////////
    // Terrence 12/03/09, for table style layout.
    // Ajax get code ready.
    insertLayoutTable: function(table_html) {
        // create a div and insert the read in table in it and set the id = TableLayoutn
        var n = this.pageNumber;
//            var tb = new Element('div', {'id':'contenttable'+n}); // ,'class':'panels_table', 'cellspacing':'2'});
        var tb = new Element('div', {'id':'contenttable'+n ,
                'class':'panels_table', 'cellspacing':'2',
                'border':'0',
                'style':'width:100%;' // table-layout is important
                });
        tb.setHTML(table_html);
        wfc_set_calculated_cell_height(tb);
        tb.id = 'contenttable'+n;
        tb.injectInside('canvas'+n);

        wfc_change_table_id(tb, n);

        // must replace the id from c? to cttd_activepage_? (this.currActive)
        return true;
    },

    // Terrence 11/23/09, drawTableStyleTab(); for table style layout
    // Ajax Get the Table code from server (must use sync mode because must get the table)
    drawTableStyleTab: function()
    {
        var table_html_text = wfc_ajax_read_table_layout_file(this.columns);
        if ($defined(table_html_text))
        {
            return this.insertLayoutTable(table_html_text); // successfully get table_x.html, insert it to (the div).
        }
        else
        {
            return false; // fail to get the layout table
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////
    // End of special layout

});
